#from flask import Flask, jsonify
import requests
from enum import Enum
import time
import hashlib
from datetime import datetime

DEBUG = False

# 游戏商提供接口，全为get
# 配置参数
app_name = "d90_university" 
app_secret = "44rjmph4-3xym-14ty-7u4o-9lastn176ytn" 
#competitionStageUUID = "6AL6KcnQaKBb"

#赛事：wHFpafamkyY2
#赛事阶段：7xQXEhyHNMBU（单排） 第二局6xMgKnBtRBFq
#6AL6KcnQaKBb（三排）

class TaskType(Enum):
    attacktask = 1
    dishafu=2
    fanhunfu=3
    qinglong=4
    baoku=5
    leitai=6

def GetHeader():
    global app_name
    global app_secret
    # 获取当前时间戳（秒级）
    timestamp = int(time.time())

    # 构建 X-Request-Token
    token_string = f"{app_name}_{timestamp}_{app_secret}"
    x_request_token = hashlib.md5(token_string.encode()).hexdigest()
    return {
        "X-Request-User": app_name,
        "X-Request-Ts": str(timestamp),
        "X-Request-Token": x_request_token
    }

# 实时积分接口
# url  https://bdapi.gameyw.netease.com/compete_api/i/v1/l22/comp/team/rank_list?
# competition_stage_uuid
# complete_stage_list
def GetRealtimeScore(suuid: str, lis: int):
    global DEBUG

    EXTERNAL_API_URL = f"https://bdapi.gameyw.netease.com/compete_api/i/v1/l22/comp/team/rank_list?competition_stage_uuid={suuid}&complete_stage_list={lis}"
    try:
        header = GetHeader()
        response = requests.get(EXTERNAL_API_URL, headers = header)
        response.raise_for_status()  # 检查请求是否成功
        external_data = response.json()  # 获取 JSON 数据
        if DEBUG:
            print(f"{suuid}实时积分请求成功:\n", response.json())
        if "code" in external_data:
            if external_data["code"] == 404:
                print("GetRealtimeScore 返回了none")
                file_name = "GetRealtimeScore.txt"
                now = datetime.now()
                # 格式化为字符串，格式为 "HH:MM:SS"
                current_time_str = now.strftime("%H:%M:%S")
                with open(file_name, "a", encoding="utf-8") as file:
                    file.write(f"{current_time_str}\n"+str(response.json())+"\n")
                return None
    except requests.exceptions.RequestException as e:
        print(str(e))
        #return jsonify({'error': str(e)}), 500
        return None
    return external_data

# 地煞符、追击任务、返魂符、回阳境等实时接口
# url https://bdapi.gameyw.netease.com/compete_api/i/v1/l22/comp/real_data/query?
# competition_stage_uuid
# mode
# mode=attacktask #追击任务
# mode=dishafu #地煞符
# mode=fanhunfu #返魂符
# mode=qinglong #四象之力
# mode=baoku #宝窟
# mode=leitai #回阳境
def GetTask(tasktype: TaskType, suuid: str):
    global DEBUG
    file_name = "example.txt"
    header = GetHeader()
    mytype = "attacktask"
    print("事件类型 ")
    print(tasktype)
    if tasktype == TaskType.attacktask:
        mytype = "attacktask"
    elif tasktype == TaskType.dishafu:
        mytype = "dishafu"
    elif tasktype == TaskType.fanhunfu:
        mytype = "fanhunfu"
    elif tasktype == TaskType.qinglong:
        mytype = "qinglong"
    elif tasktype == TaskType.baoku:
        mytype = "baoku"
    elif tasktype == TaskType.leitai:
        mytype = "leitai"
    EXTERNAL_API_URL = f"https://bdapi.gameyw.netease.com/compete_api/i/v1/l22/comp/real_data/query?competition_stage_uuid={suuid}&mode={mytype}"
    try:
        response = requests.get(EXTERNAL_API_URL, headers = header)
        response.raise_for_status()  # 检查请求是否成功
        external_data = response.json()  # 获取 JSON 数据
        if DEBUG:
            print(f"{EXTERNAL_API_URL}事件请求成功:\n", response.json())
            # with open(file_name, "a", encoding="utf-8") as file:
            #     file.write(str(response.json())+"\n")
        if "code" in external_data:
            if external_data["code"] == 404:
                print("GetTask 返回了none")
                file_name = "GetTask.txt"
                now = datetime.now()
                # 格式化为字符串，格式为 "HH:MM:SS"
                current_time_str = now.strftime("%H:%M:%S")
                with open(file_name, "a", encoding="utf-8") as file:
                    file.write(f"{current_time_str}\n"+str(response.json())+"\n")
                return None
    except requests.exceptions.RequestException as e:
        print(str(e))
        #return jsonify({'error': str(e)}), 500
        return None
    return external_data

# 赛前落点及英雄选择接口   考虑的是比赛一开始我系统自动记录一下，别人来请求查看一下，没有的话重新请求一遍
# url https://bdapi.gameyw.netease.com/compete_api/i/v1/l22/comp/before_real_data/query?
# competition_stage_uuid
def GetPosAndHero(suuid: str):
    global DEBUG
    header = GetHeader()
    EXTERNAL_API_URL = f"https://bdapi.gameyw.netease.com/compete_api/i/v1/l22/comp/before_real_data/query?competition_stage_uuid={suuid}"
    try:
        response = requests.get(EXTERNAL_API_URL, headers = header)
        response.raise_for_status()  # 检查请求是否成功
        external_data = response.json()  # 获取 JSON 数据
        if DEBUG:
            print(f"{suuid}赛前落点请求成功:\n", response.json())
        if "code" in external_data:
            if external_data["code"] == 404:
                print("GetPosAndHero 返回了none")
                file_name = "GetPosAndHero.txt"
                now = datetime.now()
                # 格式化为字符串，格式为 "HH:MM:SS"
                current_time_str = now.strftime("%H:%M:%S")
                with open(file_name, "a", encoding="utf-8") as file:
                    file.write(f"{current_time_str}\n"+str(response.json())+"\n")
                return None
    except requests.exceptions.RequestException as e:
        print(str(e))
        #return jsonify({'error': str(e)}), 500
        return None
    return external_data

# # 英雄阵容选择数据接口
# # url https://bdapi.gameyw.netease.com/compete_api/i/v1/d90/live/comp/hero/pick?
# # competitionUUID
# # competitionStageUUID
# # mode_id
# # agg_by
# def GetHeroLineup(uuid: str, suuid: str):
#     global DEBUG
#     header = GetHeader()
#     EXTERNAL_API_URL = f"https://bdapi.gameyw.netease.com/compete_api/i/v1/d90/live/comp/hero/pick?competitionUUID={uuid}&competitionStageUUID={suuid}"
#     try:
#         response = requests.get(EXTERNAL_API_URL, headers = header)
#         response.raise_for_status()  # 检查请求是否成功
#         external_data = response.json()  # 获取 JSON 数据
#         if DEBUG:
#             print(f"{uuid}  {suuid}英雄阵容请求成功:\n", response.json())
#         if "code" in external_data:
#             if external_data["code"] == 404:
#                 print("GetHeroLineup 返回了none")
#                 file_name = "GetHeroLineup.txt"
#                 now = datetime.now()
#                 # 格式化为字符串，格式为 "HH:MM:SS"
#                 current_time_str = now.strftime("%H:%M:%S")
#                 with open(file_name, "a", encoding="utf-8") as file:
#                     file.write(f"{current_time_str}\n"+str(response.json())+"\n")
#                 return None
#     except requests.exceptions.RequestException as e:
#         print(str(e))
#         #return jsonify({'error': str(e)}), 500
#         return None
#     return external_data

# 赛程信息接口（用于获取单局UUID）
# url https://bdapi.gameyw.netease.com/compete_api/i/v1/d90/comp/schedule/result?
# 传赛事阶段uuid？
def GetMatchStage(suuid: str):
    global DEBUG
    header = GetHeader()
    EXTERNAL_API_URL = f"https://bdapi.gameyw.netease.com/compete_api/i/v1/d90/comp/schedule/result?stage_uuid={suuid}"
    try:
        response = requests.get(EXTERNAL_API_URL, headers = header)
        response.raise_for_status()  # 检查请求是否成功
        external_data = response.json()  # 获取 JSON 数据
        if DEBUG:
            print(f"{suuid}赛程信息请求成功:\n", response.json())
        if "code" in external_data:
            if external_data["code"] == 404:
                print("GetMatchStage 返回了none")
                file_name = "GetMatchStage.txt"
                now = datetime.now()
                # 格式化为字符串，格式为 "HH:MM:SS"
                current_time_str = now.strftime("%H:%M:%S")
                with open(file_name, "a", encoding="utf-8") as file:
                    file.write(f"{current_time_str}\n"+str(response.json())+"\n")
                return None
    except requests.exceptions.RequestException as e:
        print(str(e))
        #return jsonify({'error': str(e)}), 500
        return None
    return external_data

# # 单局数据接口
# # url https://bdapi.gameyw.netease.com/compete_api/i/v1/d90/comp/match/result?match_uuid=ZAvFAMcKnHLu
# # 传赛局uuid ？
# def GetSingleData(muuid: str):
#     global DEBUG
#     header = GetHeader()
#     EXTERNAL_API_URL = f"https://bdapi.gameyw.netease.com/compete_api/i/v1/d90/comp/match/result?match_uuid={muuid}"
#     try:
#         response = requests.get(EXTERNAL_API_URL, headers = header)
#         response.raise_for_status()  # 检查请求是否成功
#         external_data = response.json()  # 获取 JSON 数据
#         if DEBUG:
#             print(f"{muuid}单局数据请求成功:\n", response.json())
#         if "code" in external_data:
#             if external_data["code"] == 404:
#                 print("GetSingleData 返回了none")
#                 file_name = "GetSingleData.txt"
#                 now = datetime.now()
#                 # 格式化为字符串，格式为 "HH:MM:SS"
#                 current_time_str = now.strftime("%H:%M:%S")
#                 with open(file_name, "a", encoding="utf-8") as file:
#                     file.write(f"{current_time_str}\n"+str(response.json())+"\n")
#                 return None
#     except requests.exceptions.RequestException as e:
#         print(str(e))
#         return None
#     return external_data
